package com.mall.untils.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Hashtable;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.mall.untils.Constants;
import com.mall.untils.UploadImgOrRecorderUtil;
/**
 * 
 * 生产二维码
 * 
 * 
 *
 */
public class MatrixToImageUtil {
	
	static Logger logger = LoggerFactory.getLogger(MatrixToImageUtil.class);
	/**
	 * 二维码生产
	 * @param request_url
	 * @param request
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static String web_matrix_to_img(String request_url,HttpServletRequest request){
        int width = 400;  
        int height = 400;  
        String format = "png";    
        String url="";
		try {
			Hashtable hints= new Hashtable();  
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8");  
			BitMatrix bitMatrix;
			bitMatrix = new MultiFormatWriter().encode(request_url, BarcodeFormat.QR_CODE, width, height,hints);
			String endpoint = request.getSession().getServletContext().getRealPath("") + File.separator + "core.jpeg";
			File outputFile = new File(endpoint);
			MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
			File file = new File(endpoint);
			if(file.exists()){
				InputStream in = new FileInputStream(file);
				String fileName="img_" + System.currentTimeMillis() + "_1.png" ;
				url = "http://ideal.oss-cn-beijing.aliyuncs.com/"+fileName;
				UploadImgOrRecorderUtil.putObject(Constants.BUCKETNAME, fileName, in, file.length());
			}
			file.delete();
			logger.info("二维码生产成功！");
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("二维码生产失败！");
		}  
		return url;
	}
	
}
